package com.etl.component.file.center;

import cn.hutool.core.util.StrUtil;
import com.component.api.model.dto.FileCenterConfigDTO;
import com.common.utils.constant.Constants;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.errors.*;
import org.apache.commons.lang3.StringUtils;

import java.io.InputStream;

/**
 * 描述：
 * minio文件中心服务
 * @author xianggj
 * @Date 2021/12/1 11:25
 **/
public class MinioFileCenter implements FileCenter {
    @Override
    public InputStream getFileStream(FileCenterConfigDTO confg, String path) throws Exception{
        MinioClient client = MinioClient.builder()
                .endpoint(confg.getUrl())
                .credentials(confg.getName(), confg.getPwd())
                .build();
        String[] strings = pathToBucket(path);
        InputStream in = client.getObject(GetObjectArgs.builder()
                .bucket(strings[0]).object(strings[1]).build());
        return in;
    }

    /**
     * 转换路径为bucket和object
     * @param path
     * @return
     */
    public String[] pathToBucket(String path) {
        path = StringUtils.startsWith(path, Constants.SLASH)?
                StringUtils.substring(path, 1):path;
        String bucket = StrUtil.subBefore(path, Constants.SLASH, false);
        String object = StrUtil.subAfter(path, Constants.SLASH, false);
        return new String[]{bucket, object};
    }
}
